<?php
class Model_Clan extends Model_WotHub {
    const CR_TEAM_ALL  = 1;
    const CR_TEAM_OFF = 2;
    const CR_TEAM_STRAT = 3;
    
    const CR_EVENT_ALL = 1;
    const CR_EVENT_OFF = 2;
    const CR_EVENT_STRAT = 3;
    
    const TYPE_MOD = 1;
    const TYPE_LIEN = 2;
    const TYPE_FILTRE = 3;
    
    private static $_baseUri = 'http://api.worldoftanks.eu/wot/clan/';
    private $_params = null;
    
    public function getClanInfo($clanId){
        $url = self::$_baseUri.'info/?application_id='.$this->_appId.'&clan_id='.$clanId;
        $data_clan = $this->api_get_content($url, 'claninfos.json');
        $data = json_decode($data_clan, true);
        return $data['data'][$clanId];
    }
    
    public function getMembreClanInfo($accountid) {
        $url = self::$_baseUri.'membersinfo/?application_id='.$this->_appId.'&member_id='.$accountid;
        $data_clan = $this->api_get_content($url, 'memberinfos.json');
        $data = json_decode($data_clan, true);
        return $data['data'][$accountid];
    }
    
    public static function getMembres($clanId) {
        $dataMembres = self::_getMembres($clanId);
        foreach ($dataMembres as $membre) {
            $membres[] = $membre['account_id'];
        }
        return $membres;
    }
    
    public static function getMembresPseudo($clanId) {
        $membres = array();
        if ($clanId !== 0) {
            $dataMembres = self::_getMembres($clanId);
            foreach ($dataMembres as $membre) {
                $membres[$membre['account_id']] = $membre['account_name'];
            }
        }
        return $membres;
    }
    
    private static function _getMembres($clanId, $liste= true) {
        $membres = array();
        if ($_SESSION['accountInfo']['clanId'] === 0) {
            return array();
        }
        if (isset($_SESSION['clanInfo']['members']) === true && count($_SESSION['clanInfo']) > 0) {
            $dataMembres = $_SESSION['clanInfo']['members'];
        }
        else {
            $url = self::$_baseUri.'info/?application_id='.$_SESSION['appId'].'&clan_id='.$clanId;
            $data_clan = self::api_get_content($url, 'claninfos.json');
            $data = json_decode($data_clan, true);
            $dataMembres = $data['data'][$clanId]['members'];
        }
        if ($liste === true) {
            return $dataMembres;
        }
        else {
            return implode(',', array_keys($dataMembres));
        }
    } 
    
    public static function getClanStat($clanId) {
        global $application;
        $clanStats = array();
        $pdo = new smartbokModele($application['bdd']);
        $url = 'http://api.worldoftanks.eu/wot/account/info/?application_id='.$_SESSION['appId'].'&language=fr&fields=statistics.all&account_id=';
        $membres = self::_getMembres($clanId);
        $nbMembres = count($membres);
        foreach ($membres as $membre => $data) {
            $listeMembres[] = $membre;
        }
        $stats = self::_getClanStatDB($pdo, $clanId);
        if (count($stats) === 0) {
            $lstMembre = implode(',', $listeMembres);
            $statClan = self::api_get_content($url.$lstMembre, 'stats.json');
            $statClan = json_decode($statClan, true);
            foreach ($statClan['data'] as $membreStat) {
                foreach ($membreStat['statistics']['all'] as $stat => $value) {
                    if (isset($clanStats[$stat]) === true) {
                        $clanStats[$stat]+=$value;
                    }
                    else {
                        $clanStats[$stat] = $value;
                    }
                }
            }

            $nbTank = $pdo->executerSql('SELECT COUNT(*) nb FROM garage WHERE account_id IN ('.$lstMembre.') AND actif = 0');
            $clanStats['tanks'] = $nbTank[0]['nb']; 
            $clanStats['membres'] = $statClan['count'];
            $clanStats['winRate'] = round((($clanStats['wins'] / $clanStats['battles']) * 100), 2);
            $listeTank = self::_getTankList($pdo);

            $clanStats['tiers'] = self::_getAvgTier($listeTank);
            self::_insertClanStat($pdo, $clanStats, $clanId);
        }
        else {
            $clanStats = $stats[0];
        }
        $clanStats = Ratings::addRatios($clanStats);
        return $clanStats;
    }
    
    private static function _getAvgTier($tanksLevel) {
        $url = 'http://api.worldoftanks.eu/wot/account/tanks/?application_id='.$_SESSION['appId'].'&language=fr&fields=tank_id,statistics&account_id=';
        $membersList = self::_getMembres($_SESSION['accountInfo']['clanId'], false);
        $listeTank = json_decode(self::api_get_content($url.$membersList, 'listeTank.json'), true);
        $nb = 0;
        $level = 0;
        foreach ($listeTank['data'] as $member) {
            foreach ($member as $tank) {
                $nb+= $tank['statistics']['battles'];
                $level+= $tanksLevel[$tank['tank_id']]*$tank['statistics']['battles'];
            }
        }
        return $level/$nb;
    }
    
    private static function _getTankList($pdo) {
        $tankList = $pdo->executerSql('SELECT tank_id, level FROM tanks');
        $tanks = array();
        foreach ($tankList as $tank) {
            $tanks[$tank['tank_id']] = $tank['level'];
        }
        return $tanks;
    }
    
    
    
    private static function _getClanStatDB($pdo, $clanId) {
        $sql = 'SELECT * FROM clanstats WHERE clan_id=:clanid AND stat_date=:date';
        $date = date('Ymd');
        $stats = $pdo->executerSql($sql, array(':clanid' => $clanId, ':date' => $date));
        return $stats;
    }
    
    private static function _insertClanStat($pdo, $statClan, $clanId) {
        $champs = implode(',', array_keys($statClan));
        $values = implode(',', array_values($statClan));
        $sql = 'INSERT INTO clanstats (clan_id, stat_date,'.$champs.') VALUES ('.$clanId.','.date('Ymd').','.$values.')';
        $pdo->executerSql($sql);
    }
    
    public function getClanParam($clanId) {
        $clanParams[0] = array('url_forum' => null, 
                'nombre_event' => '6', 
                'creation_event' =>  '1', 
                'creation_team' => '1');
        if($this->_params === null && $clanId !== null){
            $sql = 'SELECT url_forum, nombre_event, creation_event, creation_team FROM clan where clan_id = :clanid';
            $clanParam = $this->executerSql($sql, array(':clanid' => $clanId));
            if (count($clanParam) === 0) {
                if (isset($_SESSION['clanInfo']['abbreviation']) === true) {
                    $bind =  array(':clanid' => $clanId, ':clan' => $_SESSION['clanInfo']['abbreviation']);
                    $sql = 'INSERT INTO clan (clan_id, nom_clan) VALUES(:clanid, :clan)';
                    $this->executerSql($sql,$bind);
                }
                return $clanParams;
            }
            return $clanParam;
        }
        elseif($clanId === null) {
            return $clanParams;
        }
        return $this->_params;
    }
    
    public function _insererForum($clanId) {
        $sql = 'UPDATE clan SET url_forum = :url WHERE clan_id = :clanid';
        $bind =  array(':clanid' => $clanId, ':url' => $_POST['frm_url']);
        $majForum = $this->executerSql($sql, $bind);
        if ($majForum == false) {
            $bind[':clan'] = $_SESSION['clanInfo']['abbreviation'];
            $sql = 'INSERT INTO clan (clan_id, nom_clan, url_forum) VALUES(:clanid, :clan, :url)';
            $this->executerSql($sql,$bind);
        }
        $_SESSION['clanInfo']['forum'] = $_POST['frm_url'];
    }
    
    public function insererParams($clanId) {
        $this->getClanParam($clanId);
        if (isset($_POST['frm_forum']) === true && $_POST['frm_forum'] === 'Enregistrer') {
            $this->_insererForum($clanId);
        }
        if (isset($_POST['frm_strateur']) === true && $_POST['frm_strateur'] === 'Enregistrer') {
            $this->_insererStrateurs($clanId);
        }
        if (isset($_POST['frm_Manage']) === true && $_POST['frm_Manage'] === 'Enregistrer') {
            $this->_insererCreation($clanId);
        }
        if (isset($_POST['frm_Event']) === true && $_POST['frm_Event'] === 'Enregistrer') {
            $this->_insererNbEvent($clanId);
        }
    }
    
    private function _insererStrateurs($clanId) {
        $sql = 'DELETE FROM strateurs WHERE clan_id = :clanid';
        $this->executerSql($sql, array(':clanid' => $clanId));
        $sql = 'INSERT INTO strateurs (clan_id, account_id) VALUES(:clanid, :accountid)';
        if (isset($_POST['strateurs']) === true) {
            foreach ($_POST['strateurs'] as $strateur) {
                $this->executerSql($sql, array(':clanid'=>$clanId, ':accountid' => $strateur));
            }
        }
    }
    
    private function _insererCreation($clanId) {
        $sql = 'UPDATE clan SET creation_event = :event, creation_team = :team WHERE clan_id = :clanid';
        $bind =  array(':clanid' => $clanId, 
                       ':event' => $_POST['frmCreateEvent'],
                       ':team' => $_POST['frmManageTeam']
        );
        $majForum = $this->executerSql($sql, $bind);
        if ($majForum == false) {
            $bind[':clan'] = $_SESSION['clanInfo']['abbreviation'];
            $sql = 'INSERT INTO clan (clan_id, creation_event, creation_team, nom_clan) VALUES(:clanid, :event, :team, :clan)';
            $this->executerSql($sql,$bind);
        }
    }
    
    private function _insererNbEvent($clanId) {
        $sql = 'UPDATE clan SET nombre_event = :event WHERE clan_id = :clanid';
        $bind =  array(':clanid' => $clanId, 
                       ':event' => $_POST['frm_nb_Evt']);
        $majForum = $this->executerSql($sql, $bind);
        if ($majForum == false) {
            $bind[':clan'] = $_SESSION['clanInfo']['abbreviation'];
            $sql = 'INSERT INTO clan (clan_id, nombre_event, nom_clan) VALUES(:clanid, :event, :clan)';
            $this->executerSql($sql,$bind);
        }
    }
    public function enregisterCss($clan) {
        $cssFile = str_replace('modeles', 'css', __FILE__);
        $cssFile = str_replace('model_clan.php', $clan.'.css', $cssFile);
        $baseCssFile = str_replace($clan, 'vierge', $cssFile);
        $bCss = file_get_contents($baseCssFile);
        foreach ($_POST as $key => $couleur) {
            if ($key !== 'frm_Css') {
                $bCss = str_replace('#'.$key.'#', $couleur, $bCss);
            }
        }
        $file = fopen($cssFile, 'w+');
        fwrite($file, $bCss);
        fclose($file);
    }
    
    public function getStrateurs($clanId) {
        $strateurs = array();
        $sql = "SELECT account_id FROM strateurs WHERE clan_id = :clanid";
        $lstStrateurs = $this->executerSql($sql, array(':clanid' => $clanId));
        $pseudos = Model_Clan::getMembresPseudo($clanId);
        foreach ($lstStrateurs as $strateur) {
            $strateurs[$strateur['account_id']] = $pseudos[$strateur['account_id']];
        }
        return $strateurs;
    }
    
    public function getClanList($clanId) {
        $sql = 'SELECT clan_id, nom_clan FROM clan WHERE clan_id != :clanid';
        $lstClan = $this->executerSql($sql, array(':clanid' => $clanId));
        return $lstClan;
    }
    
    public function getDetail($eventId) {
        $detail = array();
        $sql = 'SELECT * from agenda_detail WHERE agenda_id = :agendaid';
        $detail = $this->executerSql($sql, array(':agendaid' => $eventId));
        if (count($detail) === 1) {
            return $detail[0];
        }
        return $detail;
    }
    
    public function ajouterDetail($agendaId) {
        //[frm_titre] => Tournoi FFL T8 [frm_visibilite] => open [frm_heavy] => 8 [frm_med] => 8 [frm_light] => 8 [frm_td] => 8 [frm_spg] => 8 )
        if (isset($_POST['frm_titre']) === true) {
            $sql = 'INSERT INTO agenda_detail (agenda_id, titre, visibilite, limite, heavy, medium, light, td, spg)
                    VALUES (:agendaid, :titre, :visiblility, :limite, :heavy, :med, :light, :td, :spg)';
            $bind = array(':agendaid' => $agendaId, 
                           ':titre' => $_POST['frm_titre'], 
                           ':visiblility' => $_POST['frm_visibilite'], 
                           ':limite' => $_POST['frm_limite'], 
                           ':heavy' => $_POST['frm_heavy'], 
                           ':med' => $_POST['frm_med'],
                           ':light' => $_POST['frm_light'], 
                           ':td' => $_POST['frm_td'],
                           ':spg' => $_POST['frm_spg']
            );
            $this->executerSql($sql, $bind);
            if (isset($_POST['frm_list_clan']) === true) {
                foreach ($_POST['frm_list_clan'] as $clan) {
                    $sql = 'INSERT INTO agenda_clan (agenda_id, clan_id) VALUES (:agendaid, :clanid)';
                   return $this->executerSql($sql, array(':agendaid' => $agendaId, ':clanid' => $clan));
                }
            }
            return false;
        }
    }
    
    public function setMessageAccueil() {
        $update = $this->executerSql('UPDATE clan SET msg_accueil = :msg WHERE clan_id=:clanid', array(':msg' => $_POST['frm_accueil'], ':clanid' => $_SESSION['clanInfo']['clan_id']));

        if ($update === 0) {
            $sql = "INSERT INTO CLAN (clan_id, nom_clan, msg_accueil) VALUES(:clanid, :nom, :msg)";
            $this->executerSql($sql, array(':msg' => $_POST['frm_accueil'], ':clanid' => $_SESSION['clanInfo']['clan_id'], ':nom' => $_SESSION['clanInfo']['abbreviation']));
        }
    }
    
    public function getMessageAccueil() {
        $sql = "SELECT msg_accueil FROM clan WHERE clan_id = :clanid";
        $msg = $this->executerSql($sql, array(':clanid' => $_SESSION['clanInfo']['clan_id']));
        if (count($msg) > 0) {
            return $msg[0]['msg_accueil'];
        }
        return false;
    }
    
    public function getTankMembresListe($lstMembres) {
        $sql = "SELECT tank_id, account_id FROM garage Where account_id in ($lstMembres) AND actif = 1";
        $liste = $this->executerSql($sql);
        return $liste;
    }
    
    public function enregistrerMod($type, $modId) {
        $bind = array(':name' => $_POST['frm_nom'],
                ':desc' => $_POST['frm_description'],
                ':lien' => str_replace('&', '&amp;', $_POST['frm_lien']));
        if ($modId === '') {
            $sql = "INSERT INTO liens (lien_type, lien_name, lien_description, lien_url, lien_clan_id) VALUES (:type, :name, :desc, :lien, :clan)";
            $bind[':clan'] = $_SESSION['accountInfo']['clanId'];
            $bind[':type'] = $type;
        }
        else {
            $sql = 'UPDATE liens SET lien_name =:name , lien_description = :desc, lien_url = :lien WHERE lien_id =:id';
            $bind[':id'] = $modId;
        }
        $this->executerSql($sql, $bind);
    }
    
    public function getModsList($type) {
        $sql = "SELECT lien_id, lien_name, lien_description, lien_url FROM liens WHERE lien_clan_id = :clanid AND lien_type = :type";
        $lstMods = $this->executerSql($sql, array(':clanid' => $_SESSION['accountInfo']['clanId'], ':type' => $type));
        return $lstMods;
    }
    
    public function deleteMod($id) {
        $sql = "DELETE FROM liens WHERE lien_id = :lienid";
        $this->executerSql($sql, array(':lienid' => $id));
    }
    
     public function deleteFiltre($id) {
        $sql = "DELETE FROM filtres WHERE filtre_id = :filtre";
        $this->executerSql($sql, array(':filtre' => $id));
        $sql = "DELETE FROM filtres_tanks WHERE filtre_id = :filtre";
        $res = $this->executerSql($sql, array(':filtre' => $id));
    }
    
    public function getFiltresList($clanOnly= false) {
        $sql = "SELECT * FROM filtres WHERE clan_id = :clanid OR clan_id IS NULL ORDER BY filtre_nom, filtre_id";
        if ($clanOnly === true) {
            $sql = "SELECT * FROM filtres WHERE clan_id = :clanid ORDER BY filtre_nom, filtre_id";
        }
        $lstFiltres = $this->executerSql($sql, array(':clanid' => $_SESSION['accountInfo']['clanId']));
        return $lstFiltres;
    }
    
    public function getFiltresDetail($eventId) {
        $sql = "SELECT * FROM filtres f
                JOIN filtres_tanks t on t.filtre_id = f.filtre_id 
                WHERE event_id LIKE '%$eventId%'  OR event_id IS NULL";
        $lstFiltres = $this->executerSql($sql);
        $filtres = array();
        foreach ($lstFiltres as $filtre) {
            $filtres[$filtre['filtre_id']]['nom'] = $filtre['filtre_nom'];
            $filtres[$filtre['filtre_id']]['tanks'][] = $filtre['tank_id'];
        }
        return $filtres;
    }
    
    public function enregistrerFiltre($filtreId) {
        $bind = array(':name' => $_POST['frm_nom'],
                      ':event' => implode('|',$_POST['frm_categorie']));
        if ($filtreId === '') {
            $sql = "INSERT INTO filtres (clan_id, filtre_nom, event_id) VALUES (:clan, :name, :event)";
            $bind[':clan'] = $_SESSION['accountInfo']['clanId'];
        }
        else {
            $sql = 'UPDATE liens SET filtre_nome =:name , event_id = :event WHERE filtre_id =:id';
            $bind[':id'] = $filtreId;
        }
        $filtreId = $this->executerSql($sql, $bind, 'filtre_id');
        $this->executerSql('DELETE FROM filtres_tanks WHERE filtre_id = :id', array(':id' => $filtreId));
        
        $tanksId = explode(',', $_POST['frm_tanks']);
        $values = '';
        foreach ($tanksId as $tankId) {
            $values .= "($filtreId, $tankId),";
        }
        $sql = 'INSERT INTO  filtres_tanks (filtre_id , tank_id) VALUES '.substr($values, 0,-1);
        $this->executerSql($sql);
    }
    
    public function getClanMembersTanks($lstMembre) {
        $url ='http://api.worldoftanks.eu/wot/account/tanks/?application_id='.$this->_appId.'&fields=statistics,tank_id&account_id='.$lstMembre;
        $data_clan = $this->api_get_content($url, 'clanmembertank.json');
        $data = json_decode($data_clan, true);
        return $data['data'];
    }
    
    public function getclanMembersStats($lstMembre) {
        $url = Model_Membre::$_baseUri.'info/?application_id='.$this->_appId.'&fields=statistics,nickname&account_id='.$lstMembre;
        $data_clan = $this->api_get_content($url, 'clanmemberstat.json');
        $data = json_decode($data_clan, true);
        return $data['data'];
    }
}
